from django_redis import get_redis_connection
from rest_framework import serializers

from users.models import User

from .models import OAuthQQUser
from .utils import decode_sign_openid


class OAuthQQUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='加密openid')
    # mobile = serializers.CharField(label='手机号', min_length=11, max_length=11)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    sms_code = serializers.CharField(label='短信验证码', min_length=6, max_length=6)
    password = serializers.CharField(label='密码', min_length=8, max_length=20)

    def validate(self, attrs):
        # 校验openid
        openid = decode_sign_openid(attrs['access_token'])
        if not openid:
            raise serializers.ValidationError('openid错误')
        # 校验sms_code
        mobile = attrs['mobile']
        sms_code = attrs['sms_code']

        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_code_%s' % mobile)

        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码已经过期")

        if sms_code != redis_sms_code:
            raise serializers.ValidationError('短信验证码填写错误')

        # 校验密码
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            # 判断密码是否正确
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码填写错误')
        attrs['openid'] = openid
        attrs['user'] = user
        return attrs


    def create(self, validated_data):

        # 获取数据
        openid = validated_data['openid']
        user = validated_data['user']

        if not user:
            user = User.objects.create_user(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile']
            )
            # 闯将商城用户绑定QQ用户
        OAuthQQUser.objects.create(openid=openid, user=user)
        return user





